package com.wenjiang.config.handler;

import com.wenjiang.common.annotation.TokenUserId;
import com.wenjiang.common.exception.TokenException;
import com.wenjiang.common.util.JWTUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
public class TokenToUserIdHandler implements HandlerMethodArgumentResolver {
    public TokenToUserIdHandler() {
        super();
    }

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if(methodParameter.hasParameterAnnotation(TokenUserId.class)){
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {


        //判断token是否为空

        String token = nativeWebRequest.getHeader("token");

        if(token==null){
            throw  new TokenException();
        }

        if(JWTUtil.isExpired(token)){
            throw  new TokenException();
        }



        return JWTUtil.getUserId(token);
    }
}
